/*
 * @Author: LVGRAPE
 * @LastEditors: LVGRAPE
 */
/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2023-08-30     RealThread   first version
 */

#include <rtthread.h>
#include <board.h>
#include <drv_common.h>
#include <rtdevice.h>
#include "bootloader.h"
RT_WEAK void rt_hw_board_init()
{
    // SCB->VTOR = FLASH_APP_ADDR;
    SCB->VTOR = 0x08004000;
    extern void hw_board_init(char* clock_src, int32_t clock_src_freq, int32_t clock_target_freq);
    // extern int at32_usbd_register(void);
    // extern int rt_usbd_vcom_class_register(void);

    /* Heap initialization */
#if defined(RT_USING_HEAP)
    rt_system_heap_init((void*)HEAP_BEGIN, (void*)HEAP_END);
#endif

    hw_board_init(BSP_CLOCK_SOURCE, BSP_CLOCK_SOURCE_FREQ_MHZ, BSP_CLOCK_SYSTEM_FREQ_MHZ);

    // at32_usbd_register();
    // rt_usbd_vcom_class_register();
    /* Set the shell console output device */
#if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE)
    rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
#endif
    rt_kprintf("open\n");
    /* Board underlying hardware initialization */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif



}
void rt_hw_cpu_reset(void)
{
    // rt_kprintf("System reboot...\n");
    // SCB->VTOR = FLASH_BASE;
    rt_err_t ret = RT_EOK;
    rt_device_t wdt_dev = rt_device_find("wdt");
    rt_uint32_t timeout = 3;
    if (!wdt_dev)
    {
        rt_kprintf("can't find wdt device\n");
        return;
    }
    ret = rt_device_init(wdt_dev);
    if(ret != RT_EOK)
    {
        rt_kprintf("wdt device init failed\n");
        return;
    }
    ret = rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_START, &timeout);
    rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, &timeout);
    if(ret != RT_EOK)
    {
        rt_kprintf("wdt set timeout failed\n");
        return;
    }
    rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
    rt_kprintf("System will reboot in %d seconds...\n", timeout);
    // rt_thread_delay(1000);
    // rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
    // rt_kprintf("%d ",timeout);
    // rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
    // rt_kprintf("%d ",timeout);
    // rt_device_control(wdt_dev, RT_DEVICE_CTRL_WDT_GET_TIMEOUT, &timeout);
    // rt_kprintf("%d ",timeout);
}
